<template>
  <div class='page-quickpay'>
      <div class="headers">
          <div class="title">
              <div class="header-logo">
                    <img :src="web_info.COMPANY_LOGO" alt="">
                </div>
          </div>
      </div>
      <div class="main">
        <div class="breadcrumb">
          <span>首页</span>
          <Icon type="ios-arrow-forward" />
          <span style="color:#000;">快捷支付</span>
        </div>
        <div class="main-wrapper" v-if="!pay_success">
          <div class="order-info">
            <p class="order-title">订单信息</p>
            <div class="order-list">
              <div class="order-list-item">订单SN：{{orderInfo.orderSn}}</div>
              <div class="order-list-item">订单状态：{{orderInfo.status == 1 ? '待缴费' : orderInfo.status == 3 ?'已缴费':'已关闭'}}</div>
              <div class="order-list-item">创建时间：{{trimDate(orderInfo.createTime)}}</div>
            </div>
          </div>
          <div class="course-info">
            <div class="course-title">
              <div class="t-left">购买课程</div>
              <div class="t-right">课程单价</div>
            </div>
            <div class="course-list">
              <div class="course-list-left">{{orderInfo.courseName}}</div>
              <div class="course-list-right">￥{{orderInfo.price}}</div>
            </div>
          </div>
          <div class="pay-list">
            <span style="margin-right:20px;">支付方式</span>
            <RadioGroup v-model="payType">
              <Radio :label="1" v-if="orderPayType == 'all' || orderPayType == 'weixin'">
                  <span class="wx-way">
                    <img src="/img/pc/weixin.png" alt="">
                    微信
                  </span>
              </Radio>
              <Radio :label="2" v-if="orderPayType == 'all' || orderPayType == 'zhifubao'">
                  <span class="zfb-way">
                    <img src="/img/pc/zhifubao.png" alt="">
                    支付宝
                  </span>
              </Radio>
            </RadioGroup>
          </div>
          <div class="text-info">
            <p>总金额：<span style="color:#FF0036">￥{{orderInfo.price}}</span></p>
            <p class="argee-art">
              <Checkbox v-model="argeeArt"></Checkbox>
              同意
              <!-- <a target="_blank" href="/">《购买协议》</a> -->
              <a href="javascript:void(0);" @click="isShowArtContent = true">《购买协议》</a>
            </p>
          </div>
          <div class="pay-order">
            <span class="pay-text">应付款：</span>
            <span class="money">￥{{orderInfo.price}}</span>
            <span class="pay-btn" @click="handlePay()">支付订单</span>
          </div>
        </div>
        <div class="success-wrapper" v-if="pay_success">
          <Icon type="md-checkmark-circle" size="100"  color="#19be6b"/>
          <p>支付成功</p>
        </div>
      </div>
      
      <Modal v-model="is_show_wechat_pay" :title="$t('locale.pc.personal.t74')">
        <div style="text-align:center;">
          <img :src="wechat_pay_qr" />
        </div>
      </Modal>
      <div class="argee-agr-content" v-show="isShowArtContent">
        <div class="agr-content">
          <div class="agr-body" v-html="web_info.REGISTER_PROTOCOL"></div>
          <div class="agr-footer">
            <button type="button" class="agr-btn" @click="isShowArtContent = false">确定</button>
          </div>
        </div>
      </div>
  </div>
</template>
<script>
import { mapState, mapActions, mapMutations } from "vuex";
import { baseUrl, socketUrl } from "~/config/conf";
import { getPayOrderInfo,getQuickpayToPcAlipay } from "~/api/quickpay";
export default {
  name:"page-pc-quickpay",
  data() {
    return {
      isShowArtContent:false,
      payType:1,
      argeeArt:true,
      orderInfo:{},
      wechat_pay_qr:"",
      is_show_wechat_pay:false,
      pay_success:false,
      websock: null,
      timer: null, //节流计时器
      socketFailedCount: 0 //socket重连计数器
    };
  },
  computed: {
    ...mapState({
      token(state) {
        return state.token;
      },
      web_info(state) {
        return state.web_info;
      },
      user_info(state) {
        return state.user_info;
      },
      theme_color(state) {
        return state.theme_color;
      },
      login_type(state) {
        return state.login_type;
      },
      kl_md(state) {
        return state.kl_md;
      }
    }),
    orderId() {
      return this.$route.query.orderId;
    },
    orderSn() {
      return this.$route.query.orderSn;
    },
    orderPayType() {
      if(this.$route.query.payType == 'all' || this.$route.query.payType == 'weixin'){
        this.payType = 1;
      }else if(this.$route.query.payType == 'zhifubao'){
        this.payType = 2;
      }
      return this.$route.query.payType;
    },
  },
  created() {
    this.getOrderInfo();
    this.initWebSocket();
    if(this.$route.query.isSuccess == 1){
      this.pay_success = true;
    }
    
  },
  mounted() {},
  deactivated(){
    this.timer = null;
    this.socketFailedCount = 0;
    this.closeConnection();
  },
  destroyed(){
    this.timer = null;
    this.socketFailedCount = 0;
    this.closeConnection();
  },
  activated(){
    this.getOrderInfo();
    this.initWebSocket();
  },
  methods: {
    ...mapMutations(["SET_IS_LOADING"]),
    initWebSocket() {
      if (process.client) {
        if ("WebSocket" in window) {
          //初始化weosocket
          const wsuri = socketUrl + "payOrder/" + this.orderSn;
          this.websock = new WebSocket(wsuri);
          this.websock.onmessage = this.websocketonmessage;
          this.websock.onopen = this.websocketonopen;
          this.websock.onerror = this.websocketonerror;
          this.websock.onclose = this.websocketclose;

          window.addEventListener("beforeunload", this.closeConnection, false);
        } else {
          this.$Message.error(this.$t("locale.pc.personal.t134"));
        }
      }
    },
    websocketonopen() {
      //连接建立之后执行send方法发送数据
      clearTimeout(this.timer);
      this.timer = null;
      this.socketFailedCount = 0;
    },
    websocketonerror() {
      //连接建立失败重连
      console.log("socket连接失败！");
      this.retryConnectSocket();
    },
    websocketonmessage(e) {
      //数据接收
      console.log("收到socket:", e);
      console.log(e.data || e);
      try {
        const result = JSON.parse(e.data);
        if (result.code == 200) {
          // 付款成功
          this.pay_success = true;
          this.is_show_wechat_pay = false;
        } else {
          this.$Message.error(this.$t("locale.pc.personal.t128"));
        }
      } catch (e) {
        console.log(e);
      }
    },
    websocketsend(Data) {
      //数据发送
      this.websock.send(Data);
    },
    async websocketclose(e) {
      //关闭
      console.log("断开连接", e);
      this.retryConnectSocket();
    },
    closeConnection() {
      return new Promise((res, rej) => {
        try {
          window.removeEventListener("beforeunload", this.closeConnection);
          this.websock && this.websock.close();

          if(this.timer){
            clearTimeout(this.timer);
            this.timer = null;
            this.socketFailedCount = 0;
          }
        } catch (e) {
          console.log("关闭socket错误：", e);
        }
        res();
      }).then();
    },
    retryConnectSocket() {
      this.debounce(async () => {
        this.socketFailedCount = this.socketFailedCount + 1;
        if (this.socketFailedCount < 10) {
          await this.closeConnection();
          this.initWebSocket();
        } else {
          console.info("websocket fail to connection , please retry later!");
          this.timer = null;
        }
      }, 3000);
    },
    debounce(fn, wait) {
      return !(() => {
        if (this.timer !== null) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(fn, wait);
      })();
    },
    trimDate(date) {
        if (date) {
            let _date = new Date(date);
            let add0 = m => {
                return m < 10 ? '0' + m : m;
            };
            return `${_date.getFullYear()}-${add0(_date.getMonth() + 1)}-${add0(_date.getDate())}  ${add0(_date.getHours())}:${add0(
                _date.getMinutes()
            )}:${add0(_date.getSeconds())}`;
        } else {
            return '';
        }
    },
    async getOrderInfo(){
      console.log(this.orderSn);
      console.log("9999999999999999999");
      if(this.orderSn){
        let result = await getPayOrderInfo(this.orderSn);
        if (result && result.data && result.data.code == 200) {
          this.orderInfo = result.data.data;
        } else {
          this.$Message.error("网络波动，请稍后再试！");
        }
      }
    },
    async handlePay() {
      if(!this.argeeArt){
        this.$Message.info("请先勾选购买协议！");
        return;
      }
      if(this.orderInfo.status == 2){
          this.$Message.info("该订单已经关闭，请勿支付！");
          return;
      }
      if(this.orderInfo.status == 3){
          this.$Message.info("该订单已经缴费，请勿重复支付！");
          return;
      }
      if (process.client) {
        //获取支付类型
        let payType = this.payType;
        //支付金额
        let orderSn = this.orderInfo.orderSn;
        if (payType == 1) {
          this.wechat_pay_qr = `${baseUrl}/payOrder/pay/wx/native/unifiedOrder?orderSn=${orderSn}`;
          this.is_show_wechat_pay = true;
        } else if (payType == 2) {
          let result = await getQuickpayToPcAlipay(this.orderSn);
          // console.log(result);
          if (result && result.data && result.data.code == 200) {
            window.location.href = result.data.data;
          } else {
            this.$Message.error(
              this.$t("locale.pc.personal.t128") + result.data
                ? result.data.msg
                : null
            );
          }
        }
      }
    },
  },
};
</script>
<style lang="scss">
.page-quickpay {
  .ivu-radio-group{
    display: flex;
  }
  .ivu-radio-wrapper.ivu-radio-group-item{
    display: flex;
    align-items: center;
  }
}

</style>
<style lang='scss' scoped>
.page-quickpay {
//   width: 1200px;
    width: 100%;
  min-height: 100vh;
  margin: 0 auto;
  .headers{
      border-bottom: 1px solid #ccc;
    background: #fff;
      .title{
            width: 80%;
            margin: auto;
            max-width: 1200px;
            background: #fff;
            padding: 6px 0;
            .header-logo{
                width: 222px;
                margin-right: 8px;
                height: 60px;
                overflow: hidden;
                display: flex;
                align-items: center;
            }
      }
  }
  .main{
    .breadcrumb{
      // color: #999;
      width: 80%;
      margin: auto;
      max-width: 1200px;
      font-size: 12px;
      padding: 25px 0px;
    }
    .main-wrapper{
      width: 80%;
      margin: auto;
      max-width: 1200px;
      background: #fff;
      padding: 20px;
      .order-info{
        .order-title{
          height: 42px;
          line-height: 42px;
          font-size: 16px;
          padding: 0 28px;
          background: #f2f5fa;
          border: 1px solid #dfe5ef;
        }
        .order-list{
          display: flex;
          justify-content: space-around;
          border-right: 1px solid #dfe5ef;
          border-left: 1px solid #dfe5ef;
          border-bottom: 1px solid #dfe5ef;
          color: #333;
          font-size: 16px;
          .order-list-item{
            padding: 15px 0;
          }
        }
      }
      .course-info{
        margin-top: 40px;
        .course-title{
          display: flex;
          justify-content: space-between;
          padding: 0 28px;
          background: #f2f5fa;
          border: 1px solid #dfe5ef;
          font-size: 16px;
          height: 42px;
          line-height: 42px;
        }
        .course-list{
          display: flex;
          justify-content: space-between;
          border-right: 1px solid #dfe5ef;
          border-left: 1px solid #dfe5ef;
          border-bottom: 1px solid #dfe5ef;
          color: #333;
          font-size: 16px;
          box-sizing: border-box;
          padding: 0 10px;
          .course-list-left,.course-list-right{
            padding: 15px 0;
          }
          .course-list-left{
            width: 80%;
          }
          .course-list-right{
            width: 10%;
            text-align: center;
          }
        }
      }
      .pay-list{
        margin: 20px 0 22px;
        padding: 0 28px;
        font-size: 16px;
        display: flex;
        align-items: center;
        .wx-way,.zfb-way{
          padding: 0px 11px;
          margin-left: 15px;
          border-radius: 4px;
          font-size: 16px;
          display: inline-flex;
          align-items: center;
        }
        .wx-way{
          border: 1px solid #00c800;
          margin-right: 20px;
        }
        .zfb-way{
          border: 1px solid #2194d3;
        }
      }
      .text-info{
        text-align: right;
        font-size: 16px;
        color: #666666;
        margin-top: 20px;
        margin-bottom: 20px;
        padding-right: 22px;
        box-sizing: border-box;
        p{
          margin-bottom: 7px;
        }
        a{
          color: #2194d2;
          text-decoration: none;
        }
      }
      .pay-order{
        background: #f2f5fa;
        padding: 20px 34px;
        // text-align: right;
        font-size: 16px;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        .money{
          font-size: 24px;
          color: #FF0036;
          // font-weight: bold;
        }
        .pay-btn{
          display: inline-block;
          padding: 5px 20px;
          color: #fff;
          border: none;
          outline: none;
          background: #FF0036;
          margin-left: 10px;
          border-radius: 4px;
          cursor: pointer;
          // font-size: 24px;
          font-size: 16px;
          height: 38px;
          line-height: 28px;
        }
      }
    }
    .success-wrapper{
      width: 80%;
      margin: auto;
      max-width: 1200px;
      background: #fff;
      padding: 80px;
      font-size: 30px;
      text-align: center;
      p{
        margin-top: 10px;
      }
    }
    
  }
  .argee-agr-content{
    z-index: 1005;
    overflow: hidden;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0,0,0,.3);
    .agr-content{
      position: relative;
      top: 100px;
      width: 800px;
      margin: 0 auto;
      background-color: #fff;
      z-index: 1005;
      outline: 0;
      border-radius: 3px;
      overflow: hidden;
      .agr-body{
        padding: 15px 30px 15px 35px;
        font-size: 12px;
        line-height: 1.5;
        max-height: 70vh;
        overflow-y: auto;
      }
      .agr-footer{
        padding: 12px 0;
        background-color: #f7f7f7;
        text-align: center;
        .agr-btn{
            background-color: #FF0036;
            border-color: #FF0036;
            color: #fff;
            padding: 0 15px;
            height: 32px;
            border-width: 1px;
            border-style: solid;
            border-radius: 3px;
            font-size: 14px;
            line-height: 30px;
            box-sizing: border-box;
            cursor: pointer;
        }
      }
    }
  }
}
</style>